package com.trade.common.utils.email;


import com.trade.common.utils.XaUtil;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Date;
import java.util.Properties;


/**
 * 邮箱发送
 * Created with IntelliJ IDEA.
 * User: lsk
 * Date: 2017/1/13
 */
public class MailUtil {
    /**
     * 邮件发送
     * 多个收件人地址之间用英文逗号(,)分隔
     * @param mailInfo
     * @return
     */
    public static boolean sendHtmlEmail(MailBean mailInfo){
        //判断是否需要身份认证
        MyAuthenticator authenticator = null;
        Properties properties = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            // 如果需要身份认证，则创建一个密码验证器
            authenticator = new MyAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
        }

        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getInstance(properties, authenticator);
        try{
            Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息
            Address from = new InternetAddress(mailInfo.getSender());//创建邮件发送者地址
            mailMessage.setFrom(from);//设置邮件消息的发送者

            //创建邮件的接收者地址
            String[] arr = mailInfo.getReceiver().split(",");
            InternetAddress[] address = new InternetAddress[arr.length];
            for (int i = 0; i < arr.length; i++) {
                address[i] = new InternetAddress(arr[i]);
            }
            mailMessage.addRecipients(Message.RecipientType.TO, address);//设置邮件消息的接收者
            mailMessage.setSubject(XaUtil.isNotEmpty(mailInfo.getSubject()) ? mailInfo.getSubject() : "无主题");//设置邮件消息的主题
            mailMessage.setSentDate(new Date());//设置邮件消息发送的时间

            //MimeMultipart类是一个容器类，包含MimeBodyPart类型的对象
            Multipart mainPart = new MimeMultipart();
            MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含HTML内容的MimeBodyPart
            //设置HTML内容
            messageBodyPart.setContent(mailInfo.getMessage(),"text/html; charset=utf-8");
            mainPart.addBodyPart(messageBodyPart);

            //存在附件
            if (XaUtil.isNotEmpty(mailInfo.getAttachFileNameList())) {
                for(String filePath:mailInfo.getAttachFileNameList()){
                    messageBodyPart = new MimeBodyPart();
                    File file = new File(filePath);
                    if(file.exists()){//附件存在磁盘中
                        FileDataSource fds = new FileDataSource(file);//得到数据源
                        messageBodyPart.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart
                        messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPart
                        mainPart.addBodyPart(messageBodyPart);
                    }
                }
            }

            //将MimeMultipart对象设置为邮件内容
            mailMessage.setContent(mainPart);
            Transport.send(mailMessage);//发送邮件
            return true;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 测试
     */
/*    public static void main(String[] ars){
        MailBean mailBean = new MailBean();
        mailBean.setMessage("测试信息");
        mailBean.setReceiver("852378249@qq.com,15809236082@163.com");
        mailBean.setSubject("测试");
        List<String> files = new ArrayList<String>();
        files.add("D:"+File.separator+"template1.html");
        mailBean.setAttachFileNameList(files);
        MailUtil.sendHtmlEmail(mailBean);
    }*/
}





